import 'dart:developer';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/entity/expert/zq_hot_expert_entity.dart';
import 'package:sports_new/entity/expert/plan_filter_entity.dart';
import 'package:sports_new/entity/match/expert_views_entity.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/server/api/expert_api.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/utils.dart';
import '../../server/api/home_api.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';

class ExpertPageLogic extends BaseController with GetTickerProviderStateMixin {
  int sportsId = 1;
  List<ResourceEntity>? lbt;
  List<ResourceEntity> menus = [];
  ResourceEntity? couponPack;
  List<List<HotExpertEntity>?> hotExpert = [null, null];
  List<PlanEntity>? list;
  late final List<List<PlanEntity>?> _pageList =
      List.generate(tabs.length, (index) => null);
  late List<String> tabs;
  late List<String> hotFilter;
  final List<int> hotTabId = [1, 4, 2, 3, 5];
  late List<int> tabId;
  final EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);
  final ScrollController refreshScroll = ApmScrollController();
  late List<List<List<PlanEntity>>?> pages =
      List.generate(tabs.length, (index) => null);
  PlanFilterEntity? menu;
  double menuScale = 0;
  int pageSize = 15;
  int _tabIndex = 1;
  int hotTabIndex = 0;
  bool toTop = false;
  bool _showMenu = false;
  TabController? hotController;
  late final ScrollController hotScroll = ApmScrollController();
  late TabController tabController =
      TabController(length: tabs.length, vsync: this, initialIndex: 1);
  late List<int> loadIndex = List.generate(tabs.length, (index) => 1);
  late AnimationController menuController;
  late Animation<double> menuAnimation;
  Map<int, Filter> _menuChoice = {};
  Map<int, int> _menuIndex = {0: 0};
  bool carouselPlay = true;

  int get tabIndex => _tabIndex;

  bool get showMenu => _showMenu;

  Map<int, int> get menuIndex => _menuIndex;

  Map<int, Filter> get menuChoice => _menuChoice;

  set menuChoice(Map<int, Filter> value) {
    _menuChoice = value;
    if (_menuChoice.values.first.name.hasValue) {
      if (_menuChoice.values.first.name != "全部方案") {
        tabs.replaceRange(1, 2, [_menuChoice.values.first.name ?? ""]);
      } else {
        tabs.replaceRange(1, 2, ["足球"]);
      }
    }
    loadIndex[_tabIndex] = 1;
    refreshC.resetFooter();
    getData(map: _menuChoice);
    update();
  }

  set menuIndex(Map<int, int> value) {
    _menuIndex = value;
    update();
  }

  set showMenu(bool value) {
    _showMenu = value;
    update();
  }

  set tabIndex(int value) {
    _tabIndex = value;
    if (1 == sportsId) {
      SpUtils.expertZqContentIndex = value;
    } else {
      SpUtils.expertLqContentIndex = value;
    }
    update();
  }

  void setHotTabIndex(int index) {
    hotTabIndex = index;
    getExpertTop(filter: index);
    if (1 == sportsId) {
      SpUtils.expertTabIndex = index;
    } else {
      SpUtils.expertLqTabIndex = index;
    }
    Utils.onEvent("caijin_hot_expert_tab", params: {"tab": hotFilter[index]});
    update();
  }

  @override
  void onInit() {
    menuController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 100));
    menuAnimation = Tween<double>(begin: 0, end: 1).animate(menuController);
    menuController.addListener(() {
      menuScale = menuController.value;
      update();
    });
    refreshScroll.addListener(() {
      if (refreshScroll.offset >= refreshScroll.position.maxScrollExtent &&
          toTop == false) {
        toTop = true;
        update();
      }
      if (refreshScroll.offset < refreshScroll.position.maxScrollExtent &&
          toTop == true) {
        toTop = false;
        update();
      }
    });
    update();
    super.onInit();
  }

  @override
  void onReady() async {
    getExpertTop(filter: hotTabIndex);

    await getResource();
    getData();
    tabController.addListener(() {
      tabIndex = tabController.index;
      getData();
      refreshC.resetFooter();
      if (showMenu) {
        showMenu = false;
        menuController.reverse();
      }
    });
    refreshScroll.addListener(() {
      if (refreshScroll.offset >= 40 && carouselPlay) {
        carouselPlay = false;
        update(["carousel"]);
      } else if (refreshScroll.offset <= 40 && !carouselPlay) {
        carouselPlay = true;
        update(["carousel"]);
      }
    });
    super.onReady();
  }

  void checkSports(int id) {
    sportsId = id;
    hotTabIndex = (1 == id
        ? (SpUtils.expertTabIndex ?? 0)
        : (SpUtils.expertLqTabIndex ?? 0));
    _tabIndex = (1 == id
        ? (SpUtils.expertZqContentIndex ?? 0)
        : (SpUtils.expertLqContentIndex ?? 0));
    tabId = [0, if (sportsId == 1) 1, if (sportsId == 2) 6, 4, 2, 3, 7, 5];
    tabs = ['关注', '人气', '连红', '命中', '回报', '会员', "免费"];
    hotFilter = ["人气", "连红", "命中", "回报"];
    hotController ??= TabController(
        length: hotFilter.length, vsync: this, initialIndex: hotTabIndex);
    tabController = TabController(
        length: tabs.length, vsync: this, initialIndex: _tabIndex);
  }

  Future getData({Map<int, Filter>? map}) async {
    log("getDDDDDDDD$_tabIndex");
    if (_tabIndex == 1) {
      _pageList[_tabIndex] =
          await ExpertApi.getRenqiPlan(1, pageSize, sportsId);
    } else {
      _pageList[_tabIndex] = await ExpertApi.getHotPlan(
          1, pageSize, tabId[_tabIndex], sportsId,
          type: map);
    }

    pages[_tabIndex] = formList(_pageList[_tabIndex]);
    update();
  }

  @override
  Future getRefresh() async {
    carouselPlay = false;
    await getResource();
    await getData(map: menuChoice);
    loadIndex[_tabIndex] = 1;
    update();
    refreshC.resetFooter();
    carouselPlay = true;
  }

  @override
  Future loadMore() async {
    if (_tabIndex == 0) {
      refreshC.finishLoad(IndicatorResult.noMore);
      return;
    }
    loadIndex[_tabIndex] += 1;
    List<PlanEntity> list = [];
    if (_tabIndex == 1) {
      list = await ExpertApi.getRenqiPlan(
          loadIndex[_tabIndex], pageSize, sportsId);
    } else {
      list = await ExpertApi.getHotPlan(
          loadIndex[_tabIndex], pageSize, tabId[_tabIndex], sportsId,
          type: menuChoice);
    }

    pages[_tabIndex]?.addAll(formList(list));
    refreshC.finishLoad(
        (pages[_tabIndex]?.length ?? 0) < pageSize * loadIndex[_tabIndex]
            ? IndicatorResult.noMore
            : IndicatorResult.success);
    update();
  }

  /// 获取榜单下的专家列表
  Future getExpertTop({int? filter}) async {
    if (filter == 0 || filter == null) {
      hotExpert[sportsId - 1] =
          await ExpertApi.getRenqiExpertHot(sportsId) ?? [];
    } else {
      hotExpert[sportsId - 1] =
          await ExpertApi.getZqExpertHot(hotTabId[filter], sportsId);
    }
    update();
  }

  Future getResource() async {
    final result = await HomeApi.getResources("app_news_caijing");
    menus = result.filter((item) => item.button == "menu_item");
    var coupon =
        result.where((element) => element.button == "coupon_package").toList();
    if (coupon.hasValue) couponPack = coupon.first;
    lbt = result.where((element) => element.button == "lbt").toList();
    // menu = await ExpertApi.getMenu();
    update();
  }

  List<List<PlanEntity>> formList(List<PlanEntity>? entity) {
    List<List<PlanEntity>> list = [];
    if (entity?.isEmpty == true || entity?.length == null) {
      return [];
    }
    List<int> spot = [];
    var sportsId = entity![0].sportsId;
    var expertId = entity[0].expertId;
    for (var i = 0; i < entity.length; i++) {
      if (entity[i].sportsId != sportsId || entity[i].expertId != expertId) {
        spot.add(i);
        sportsId = entity[i].sportsId;
        expertId = entity[i].expertId;
      }
    }
    if (spot.length > 1) {
      list.add(entity.sublist(0, spot[0]));
      list.addAll(List.generate(spot.length, (index) {
        if (index == spot.length - 1) {
          return entity.sublist(spot.last, entity.length);
        }
        return entity.sublist(spot[index], spot[index + 1]);
      }));
    } else if (spot.length == 1) {
      list.add(entity.sublist(0, spot[0]));
      list.add(entity.sublist(spot[0], entity.length));
    } else {
      list.add(entity);
    }
    return list;
  }

  doRefresh() async {
    if (refreshC.headerState?.mode.isIdle == false) return;
    await refreshC.callRefresh(scrollController: refreshScroll);
  }
}
